Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.
In this article, we’ll look at some solutions to common JavaScript problems.
Difference Between DOMContentLoaded and Load Events
There’s a difference between DOMContentLoaded and load events.
DOMContentLoaded event is fired when the document is loaded and parsed without waiting for resources like stylesheets, images, and subframes to finish loading.
The load event waits for everything to finish loading.
Plus Symbol Before a Variable
The +
operator converts a non-numeric variable to a number.
For instance, if we have:
const str = '123';
const num = +str;
Then num
is 123.
Determine if String is in an Array in JavaScript
We can use the indexOf
method to check if a string is in an array.
For instance, we can write:
['foo', 'bar', 'baz'].indexOf(str) > -1
We can call indexOf
to check if str
is included in the ['foo', 'bar', 'baz']
array.
indexOf
return -1 if it’s not in the array and the index if it is.
Also, we can use the includes
method to do the same thing:
['foo', 'bar', 'baz'].includes(str)
It returns true
if it’s included and false
if it’s not.
Convert Size in Bytes to KB, MB, GB, etc. in JavaScript
We get convert the magnitude of bytes to the KB, MB, etc. by dividing the number of bytes with the power of 1024 to the power of the unit that we’re converting to.
For instance, we can write:
const formatBytes = (bytes, decimals) => {
if (bytes == 0) {
return "0 Byte";
}
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
}
We return '0 bytes'
is bytes
is 0.
To convert the bytes
to a given unit, we can divide it, by the power of 1024.
i
is the index of the sizes
array that we want to get, which is also the exponent that we want to raise 1024 to.
If we divide by 1024
, we get the size in KB.
And if we divide by 1024 ** 2
, we get the size in MB, and so on.
Now we get the size and the corresponding unit.
Include JS File in Another JS File
We can include one JS file in another JS file by creating a script tag dynamically.
For instance, we can write:
const script = document.createElement('script');
script.src = '/path/to/script';
document.head.appendChild(script);
to create the script tag.
Then we append it to the head
element to load the script.
Remove Blank Attributes from an Object in Javascript
We can remove blank attributes from an object in JavaScript by getting the keys with the Object.keys
method.
Then we can use delete
to delete the keys that have empty values.
For instance, we can write:
for (const key of Object.keys(obj)) {
if (obj[key] === null || typeof obj[key] === 'undefined') {
delete obj[key];
}
}
We loop through the keys with a for-of loop.
In the loop body, we check for null
and undefined
.
Then we use delete
to delete the property with values null
or undefined
.
Sort an Array of Objects by Single Key with Date Value
If we have an array of objects with a property that is a date string, we can use the sort
method to sort the array by the date string property.
For example, if we have the following array:
const arr = [{
updatedAt: "2012-01-01T06:25:24Z",
foo: "bar"
},
{
updatedAt: "2012-01-09T11:25:13Z",
foo: "bar"
},
{
updatedAt: "2012-01-05T04:13:24Z",
foo: "bar"
}
]
Then we can write:
const sorted = arr.sort((a, b) => {
const updatedAtA = new Date(a.updatedAt);
const updatedAtB = new Date(b.updatedAt);
return updatedAtA - updatedAtB;
});
We have a callback that subtract updatedAtA
and updatedAtB
.
This works because before they’re subtracted, they’re converted to their timestamp values first.
Therefore, we can do the sorting as a number will be returned.
Conclusion
DOMContentLoaded and load are different events.
We can sort dates directly.
The +
operator can be used to convert to numbers.
We can convert bytes to different units by doing some division.